/**
 *对Date的扩展，将 Date 转化为指定格式的String
 *月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
 *年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 *例子：
 *(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 *(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
 */
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

String.prototype.endWith = function (endStr) {
    var d = this.length - endStr.length;
    return (d >= 0 && this.lastIndexOf(endStr) == d)
}

/**
 * 获取网页地址的参数
 * @param {}} name
 */
export function GetHtmlUrlQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        let str = unescape(r[2]);
        if(EndWith(str,'/')) {
          str = str.substr(0, str.length - 1)
        }
        return str;
    }
    return '';
}

/**
 * 是否有网页地址的参数
 * @param {}} name
 */
export function IsHtmlUrlcontainString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return true;
    }
    return false;
}

//国际时间转时间戳
export function UniversalTimeToStamp(strUniversalTime){
  if (strUniversalTime.length == 0) {
      return '';
  }
  let sTime = new Date(strUniversalTime).toISOString().replace(/T/g, " ").replace(/\.[\d]{3}Z/, "");
  let date = new Date(sTime);
  var time = Date.parse(date) / 1000;
  return time;
}

//根据传入时间的分隔格式生成相应时间返回
//yyyy/MM/dd HH:mm:ss WW
export function ConversionTime(TimeFormat) {
  let str = ""
  let yy = new Date().getFullYear();
  let mm = new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1;
  let dd = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate();
  let hh = new Date().getHours()< 10 ? '0' + new Date().getHours() : new Date().getHours();
  let mf =
    new Date().getMinutes() < 10
      ? "0" + new Date().getMinutes()
      : new Date().getMinutes();
  let ss =
    new Date().getSeconds() < 10
      ? "0" + new Date().getSeconds()
      : new Date().getSeconds();
  let week = new Date().getDay();
  let ww = '';
  if (week == 1) {
    ww = "星期一";
  } else if (week == 2) {
    ww = "星期二";
  } else if (week == 3) {
    ww = "星期三";
  } else if (week == 4) {
    ww = "星期四";
  } else if (week == 5) {
    ww = "星期五";
  } else if (week == 6) {
    ww = "星期六";
  } else {
    ww = "星期日";
  }
  str = TimeFormat.replace(/\b(yyyy|MM|dd|HH|mm|ss|WW)\b/g, function($0, $1) {
    return {
      "yyyy": yy,
      "MM": mm,
      "dd": dd,
      "HH": hh,
      "mm": mf,
      "ss": ss,
      "WW":ww
    }[$1];
  });

  return str;
}

//时间戳转标准时间
export function toDate(number) {
  var n = number * 1000;
  var date = new Date(n);
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  var h = (date.getHours()< 10 ? '0' + date.getHours() : date.getHours()) + ':';
  var m = (date.getMinutes()< 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
  var s = date.getSeconds()< 10 ? '0' + date.getSeconds() : date.getSeconds();
  return (Y + M + D + " " + h + m + s);
}

//国际时间转标准时间
export function UniversalTimeToStandard(strUniversalTime) {
    if (strUniversalTime.length == 0) {
        return '';
    }
    let sTime = new Date(strUniversalTime).toISOString().replace(/T/g, " ").replace(/\.[\d]{3}Z/, "");
    return sTime;
}

//日期字符串转时间戳（毫秒）
export function strToTimestamp(strTime) {
  let sData = new Date(strTime);
  return sData.getTime();
}

//时间戳转日期(毫秒)
export function timestampToData(timestamp) {
  let date = new Date(timestamp);
  return date;
}

//日期转时间戳（毫秒）
export function dateToTimestamp(data) {
  return data.getTime();
}

//日期转字符串
export function dateToStr(data) {
  let timestamp = dateToTimestamp(data);
  return toDate(timestamp/1000);
}

//日期字符串转时间戳（毫秒）
export function strToData(strTime) {
  let sData = new Date(strTime);
  return sData;
}

//获取当前时间戳（毫秒）
export function getCurTimestamp() {
  let sData = new Date();
  return sData.getTime();
}

export function MyWriteLog() {
    var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
    //获取当前时间
    let date = new Date();
    let strDate = date.format("yyyy-MM-dd hh-mm-ss");
    console.log(strDate, args);
}

//中国标准时间转北京时间格式
export function StandardToBeijingtime(Standardtime) {
  var Beijintime = new Date(Standardtime);
  var Y = Beijintime.getFullYear() + '-';
  var M = (Beijintime.getMonth() + 1 < 10 ? '0' + (Beijintime.getMonth() + 1) : Beijintime.getMonth() + 1) + '-';
  var D = Beijintime.getDate()<10 ? '0' + Beijintime.getDate() : Beijintime.getDate();
  var h = (Beijintime.getHours()< 10 ? '0' + Beijintime.getHours() : Beijintime.getHours()) + ':';
  var m = (Beijintime.getMinutes()< 10 ? '0' + Beijintime.getMinutes() : Beijintime.getMinutes()) + ':';
  var s = Beijintime.getSeconds()< 10 ? '0' + Beijintime.getSeconds() : Beijintime.getSeconds();
  var datetime=(Y + M + D + " " + h + m + s)
  return datetime;
}

/**
 * 判断是否后缀
 * @param strOrigin
 * @param strFlag
 * @returns {boolean|boolean}
 * @constructor
 */
export function EndWith(strOrigin,strFlag) {
  var d = strOrigin.length - strFlag.length;
  return (d>=0&&strOrigin.lastIndexOf(strFlag)==d);
}


/**
 * 获取QtController
 * @param {*} strJsonParam
 */
export function GetQtController() {
    return window.qtController;
}

export function IsFrameType() {
  let isFrame = GetHtmlUrlQueryString('isFrame');
  if(isFrame == 1) {
    return true;
  }
  return false;
}

export function Queue(size) {
    var list = [];

    //向队列中添加数据
    this.push = function (data) {
        if (data == null) {
            return false;
        }
        //如果传递了size参数就设置了队列的大小
        if (size != null && !isNaN(size)) {
            if (list.length == size) {
                this.pop();
            }
        }
        list.unshift(data);
        return true;
    }

    //从队列中取出数据
    this.pop = function () {
        return list.pop();
    }

    //返回队列的大小
    this.size = function () {
        return list.length;
    }

    //返回队列的内容
    this.quere = function () {
        return list;
    }

    this.remove = function (index) {
        list.splice(index, 1);
    }

    this.clear = function () {
      while (list.length > 0) {
        this.pop();
      }
    }
}

/**
 * PubSub管理类
 */
export class PubSubManager {
  static eventMap = new Map();
  static isFind = false;

  static addEvent(object,event,fnCallback) {
    if(!PubSubManager.eventMap.has(object)) {
      PubSubManager.eventMap.set(object,new Array());
    }
    if(PubSubManager.eventMap.get(object).indexOf(event) == -1) {
      PubSubManager.eventMap.get(object).push(event);
      PubSub.subscribe(event, fnCallback);
    }
  }

  static removeEvent(object) {
    if(object instanceof String) {
      PubSubManager.eventMap.forEach(function (value, key, map) {
        let list = value;
        for(let index in list) {
          if(list[index] == object) {
            list.slice(index,1);
            PubSub.unsubscribe(object);
            return;
          }
        }
      });
    }else if(object instanceof Object) {
      let otherList = [];
      PubSubManager.eventMap.forEach(function (value, key, map) {
        if(key != object) {
          otherList = otherList.concat(value);
        }
      });

      let selfList = PubSubManager.eventMap.get(object);
      for(let index in selfList) {
        if(otherList.indexOf(selfList[index]) == -1) {
          PubSub.unsubscribe(selfList[index]);
        }
      }
      PubSubManager.eventMap.delete(object);
    }
  }

  static sendMessage(msg,dataArray = [],excludeComponent = [],isToAPI = false) {
      PubSub.sendPubSubMessage(msg,dataArray,excludeComponent,isToAPI);
  }
}

//存储到localStorage
export function SaveLocalStorage(key,value) {
  localStorage.setItem(key, value);
}

//localStorage 获取
export function GetLocalStorage(key) {
  let value = localStorage.getItem(key);
  return value;
}

//localStorage 删除某个key
export function DeleteLocalStorageByKey(key) {
  localStorage.removeItem(key);
}

//localStorage 删除所有
export function DeleteLocalStorageAll() {
  localStorage.clear()
}

//存储到SessionStorage
export function SaveSessionStorage(key,value) {
  sessionStorage.setItem(key, value);
}

//SessionStorage 获取
export function GetSessionStorage(key) {
  let value = sessionStorage.getItem(key);
  return value;
}

//SessionStorage 删除某个key
export function DeleteSessionStorageByKey(key) {
  sessionStorage.removeItem(key);
}

//SessionStorage 删除所有
export function DeleteSessionStorageAll() {
  sessionStorage.clear()
}

//生成UUID
export function CreateUUID() {
  var temp_url = URL.createObjectURL(new Blob());
  var uuid = temp_url.toString(); // blob:https://xxx.com/b250d159-e1b6-4a87-9002-885d90033be3
  URL.revokeObjectURL(temp_url);
  return uuid.substr(uuid.lastIndexOf("/") + 1);
}

/**
 * rgba转16进制
 * @param rgbaColor
 * @returns {string}
 * @constructor
 */
export function ColorRgbaToHex(rgbaColor) {
  let values = rgbaColor
    .replace(/rgba?\(/, '')
    .replace(/\)/, '')
    .replace(/[\s+]/g, '')
    .split(',');
  let a = parseFloat(values[3] || 1),
    r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
    g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
    b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255);
  return "#" +
    ("0" + r.toString(16)).slice(-2) +
    ("0" + g.toString(16)).slice(-2) +
    ("0" + b.toString(16)).slice(-2);
}

/**
 * 16进制颜色转rgba
 * @param hexColor
 * @returns {[]} 颜色数组
 * @constructor
 */
export function ColorHexToRgba(hexColor){
  let color = [];
  color.push(0,0,0,0);
  let pattern = /^#([0-9|a-f]{3}|[0-9|a-f]{6})$/;
  if(color && pattern.test(color)) {
    if(color.length == 4) {
      // 将三位转换为六位
      color = '#' + color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
    }
    //处理六位的颜色值
    let colorNew = [];
    for (var i=1; i<7; i+=2) {
      colorNew.push(parseInt("0x"+color.slice(i, i+2)));
    }
    return colorNew;
  }
  return color;
};
